package com.ceba.test.modules.admin.service;

import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.Iterator;

import com.ceba.base.helper.LoggerHelper;
import com.ceba.cebautils.DateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ceba.test.base.configs.CebaConfig;
import com.ceba.test.base.configs.CebaPathUtil;
import com.ceba.test.base.utils.CebaFileManageUtil;
import com.ceba.base.web.service.IBaseService;
import com.ceba.test.modules.admin.dao.BackupDao;

import abc.util.FileHelper;
import abc.util.StringUtils;

public class UpgradeService  extends IBaseService{
	private String finishMsg = "";
	
	static Logger logger = LoggerFactory.getLogger(UpgradeService.class);
	
	private BackupDao backupDao;
	
	public String getFinishMsg() {
		return this.finishMsg;
	}

	/**
	 * 备份数据库
	 * @param backupPath 数据库备份路径
	 * @return
	 */
	public Boolean backupDatabase(String backupPath,String logPath){
		log("开始备份数据库",logPath);
		try {
			if(!CebaFileManageUtil.createDirectory(backupPath)){
				return false;
			}
			if(backupDao.backup(backupPath)){
				log("备份数据库完成！",logPath);
				return true;
			}
		} catch (Exception e) {
			LoggerHelper.error(logger, e,"");
		}
		log("备份数据库失败",logPath);
		return false;
	}
	
	
	/**
	 * 执行sql文件
	 * @param sqlPath sql文件地址
	 * @return
	 */
	public Boolean upgradeSqlFile(String sqlPath,String logPath){
		log("开始执行SQL语句",logPath);
		try {
			if(FileHelper.exists(sqlPath)){
				Collection<File> files = FileHelper.listFiles(sqlPath);
				Iterator<File> iterator = files.iterator();
				File file;
				while (iterator.hasNext()) {
					file = iterator.next();
					if(FileHelper.getFileExtName(file.getName()).equals("sql")){
						backupDao.restore(file.getName());
					}
				}
			}
			log("执行SQL语句完成",logPath);
			return true;
		} catch (Exception e) {
			LoggerHelper.error(logger, e,"");
		}
		return false;
	}
	
	
	/**
	 * 执行sql
	 * @param sqlPath 升级语句的地址
	 * @return
	 * @throws IOException 
	 */
	public Boolean upgradeSql(String sqlPath,String logPath) throws Exception {
		log("开始执行SQL语句",logPath);
		Boolean bSuccess=true;
		if(FileHelper.exists(sqlPath)){
			Collection<File> files = FileHelper.listFiles(sqlPath);
			Iterator<File> iterator = files.iterator();
			File file;
			while (iterator.hasNext()) {
				file = iterator.next();
				//确定是否是sql文件
				if(FileHelper.getFileExtName(file.getName()).equals("sql")){
					try {					
						String[] sqlList = getSqlsByFile(file);
						for(String sql:sqlList){ 
							if(StringUtils.isNotNullAndEmpty(sql)){
								log("执行："+sql,logPath);
								if(backupDao.excute(sql)){
									log("执行成功",logPath);
								}
								else {
									log("执行失败",logPath);
									bSuccess=false;
								}
							}
						}
					} catch (Exception e) {
						LoggerHelper.error(logger, e,"");
					}
				}
			}
			CebaConfig.init();
			return bSuccess;
			
		}
		return bSuccess;
	}
	
	
	
	
	/**
	 * 从文件中获取sql语句
	 * @param sqlFile sql文件
	 * @return
	 * @throws Exception
	 */
	private String[] getSqlsByFile(File sqlFile) throws Exception{ 
        	String text=FileHelper.getFileContent(sqlFile);
        	String[] sqls=text.split(";--");
        return sqls;   
	}
	
	/**
	 * 执行记录
	 * @param txt
	 */
	private void log(String txt,String logPath){
		 File file=new File(logPath);
		 String content=FileHelper.getFileContent(file, "gbk");
		 if(StringUtils.isNullOrEmpty(content)){
			 content="升级开始";
		 }
		 
		 txt=content+";\r\n"+ DateUtil.getNowTime("")+"：   "+txt;
		 FileHelper.setFileContent(file, txt);
	}
	
	
	public Boolean recoverDatabase(String databasePath){
		if(backupDao.restore(databasePath)){
			return true;
		}
		return false;
	}
	
	
	
	
	
	public BackupDao getBackupDao() {
		return backupDao;
	}
	public void setBackupDao(BackupDao backupDao) {
		this.backupDao = backupDao;
	}
	
	
	
	
	
	
}
